<template>
  <a-modal
    v-model:visible="visible"
    title="选择字典数据"
    :mask-closable="false"
    :after-close="afterClose"
    :keyboard="false"
    @ok="handleOk"
  >
    <a-space>
      <a-select v-model:value="selectedAppId" style="width: 200px" placeholder="选择应用" @change="getDictType">
        <a-select-option v-for="item in apps" :key="item.appId" :value="item.appId">{{ item.appName }}</a-select-option>
      </a-select>
      <a-select v-model:value="selectedTypeId" style="width: 200px" placeholder="选择字典分类" @change="getDictData">
        <a-select-option v-for="item in dictTypes" :key="item.dictId" :value="item.dictId">
          {{ item.name }}
        </a-select-option>
      </a-select>
    </a-space>
    <div class="mt-4">
      <a-tag v-for="item in dictDatas" :key="item.dictDataId" class="mt-2">
        {{ item.name }}
      </a-tag>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { appLoadList } from '@@/api/common'
import { dictTypeQureyList, dictDataQureyList } from '@@/api/dict'

const visible = ref(false)

// 查询应用
const apps = ref<any[]>([])
const selectedAppId = ref(undefined)
appLoadList({
  pageSize: 20,
  pageNum: 1
}).then((res) => {
  apps.value = res.list
  dictDatas.value = []
  //getDictType(apps.value[0].appId)
})

// 查询字典分类
const selectedTypeId = ref(undefined)
const dictTypes = ref<any[]>([])
const getDictType = (appId) => {
  dictTypeQureyList({
    appId,
    name: '',
    dictType: 1,
    flag: '',
    dictId: '',
    pageSize: 50
  }).then((res) => {
    dictTypes.value = res.list
  })
}

// 查询字典列表
const dictDatas = ref<any[]>([])
const getDictData = () => {
  dictDataQureyList({
    appId: selectedAppId.value,
    dictType: 1,
    pageNum: 1,
    pageSize: 50,
    dictId: selectedTypeId.value
  })
    .then((res) => {
      dictDatas.value = res.list
    })
    .catch(() => {
      dictDatas.value = []
    })
}

const emits = defineEmits(['selected'])
const handleOk = function () {
  const data = dictDatas.value.map((item) => {
    return {
      value: item.value,
      label: item.name
    }
  })
  emits('selected', data)
  visible.value = false
}

const afterClose = () => {
  dictDatas.value = []
  selectedAppId.value = undefined
  selectedTypeId.value = undefined
}

const show = function () {
  visible.value = true
}

defineExpose({
  show
})
</script>

<style lang="less"></style>
